package com.example.weight.householdWaste;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.Utility;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class BottleClassifierPutrescibleActivity extends AppCompatActivity {

    private String name, factory;

    private EditText bottleWeight, comment;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottle_classifier_putrescible);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.bottle_classifier_putrescible_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                BottleClassifierPutrescibleActivity.this.finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        TextView actualDate = findViewById(R.id.textView37);
        String tempText = actualDate.getText().toString();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        actualDate.setText(tempText+year+"年"+month+"月"+day+"日");

        bottleWeight = findViewById(R.id.bottle_classifier_putrescible_weight);
        comment = findViewById(R.id.bottle_classifier_putrescible_comment);

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/bottleCorrodibleSorting/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                new AlertDialog.Builder(BottleClassifierPutrescibleActivity.this)
                                        .setTitle("今日已填写此表")
                                        .setCancelable(false)
                                        .setPositiveButton("确定", null)
                                        .show();
//                                JSONObject data = jsonObject.getJSONObject("data");
//                                bottleWeight.setText(data.getString("weight"));
//                                comment.setText(data.getString("remarks"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(BottleClassifierPutrescibleActivity.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        bottleWeight.setText(weight);
    }

    public void goWeight(View view) {
        Intent intent = new Intent(BottleClassifierPutrescibleActivity.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    public void save(View view) {
        if (!Utility.isNumeric(bottleWeight.getText().toString())) {
            Toast.makeText(this, "请填写重量", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) -> {
                // 提交表单
                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/shlj/bottleCorrodibleSorting/addForm";

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("zys", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");
//                                    bottleWeight.setText("");
//                                    comment.setText("");

                                    if (code.startsWith("2"))
                                        Toast.makeText(BottleClassifierPutrescibleActivity.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(BottleClassifierPutrescibleActivity.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(BottleClassifierPutrescibleActivity.this,
                                "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map=new HashMap<>();
                        map.put("weightstr", bottleWeight.getText().toString());
                        map.put("operator", name);
                        map.put("remarks", comment.getText().toString());
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);

            }).show();
    }
}
